package com.hhuhh.smarthome.socket.model;

import java.io.Serializable;
import java.security.interfaces.RSAPrivateKey;

import org.apache.mina.util.Base64;

import com.hhuhh.smarthome.socket.support.ResultDecoder;
import com.hhuhh.smarthome.utils.RSAHelper;

/**
 * @author John zhang
 * @version 0.1
 */
public abstract class ModelWrapper implements Serializable {

	private static final long serialVersionUID = 1942736663291587090L;
	
	private Object srcData;
	private Object value;
	
	private RSAPrivateKey rsaPriKey;

	public void wrapperResult( Object data ) {
		wrapperResult( data, null );
	}
	
	public void wrapperResult( Object data, ResultDecoder[] resultDecoders ) {
		if ( data == null )
			return;
		
		this.srcData = data;
		
		decode( data, resultDecoders );
	}
	
	private void decode( Object data, ResultDecoder[] resultDecoders ) {
		if( resultDecoders != null && resultDecoders.length != 0 ) {
			for( ResultDecoder decoder : resultDecoders ) {
				switch( decoder ) {
					case BASE64 : 
						if( srcData instanceof byte[] ) {
							value = Base64.decodeBase64 ( (byte[]) srcData );
						} else if ( srcData instanceof String ) {
							value = Base64.decodeBase64 ( ((String) srcData).getBytes () );
						}
						break;
						
					case RSA	: 
						if ( rsaPriKey == null ) break;
						
						if( srcData instanceof byte[] ) {
							value = RSAHelper.decrypt ( rsaPriKey, (byte[]) srcData );
						} else if ( srcData instanceof String ) {
							value = RSAHelper.decrypt ( rsaPriKey, ((String) srcData).getBytes () );
						}
						break;
				}
			}
		}
		
		parseResult ();
	}
	
	public abstract void parseResult();
	
	public void setRSAPriKey( RSAPrivateKey rsaPriKey ) {
		this.rsaPriKey = rsaPriKey;
	}

	public Object getValue() {
		return value;
	}
}
